import type { PageResult, PageParams, BaseResponse } from '@/types/api.d'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

/**
 * 数据源信息类型定义
 */
export interface DataSource {
  id: number
  sourceName: string
  dbType: string
  host: string
  port: number
  dbName: string
  username: string
  password: string
  timeout: number
  hospitalId: number
  createTime: string
  updateTime: string
}

/**
 * 数据源查询参数
 */
export interface DataSourceSearchParams extends PageParams {
  sourceName?: string
  dbType?: string
  hospitalId?: number
}

/**
 * 测试连接参数
 */
export interface TestConnectionParams {
  dbType: string
  host: string
  port: number
  dbName: string
  username: string
  password: string
  timeout?: number
}

/**
 * 获取数据源列表
 * @param params 查询参数
 * @returns 分页结果
 */
export const fetchDataSources = async (params: DataSourceSearchParams): Promise<PageResult<DataSource>> => {
  try {
    const { data } = await request.get<BaseResponse<PageResult<DataSource>>>('/api/datasources', { params })
    return data.data
  } catch (error) {
    ElMessage.error('获取数据源列表失败')
    throw error
  }
}

/**
 * 获取数据源详情
 * @param id 数据源ID
 * @returns 数据源详情
 */
export const getDataSource = async (id: number): Promise<DataSource> => {
  try {
    const { data } = await request.get<BaseResponse<DataSource>>(`/api/datasources/${id}`)
    return data.data
  } catch (error) {
    ElMessage.error('获取数据源详情失败')
    throw error
  }
}

/**
 * 创建数据源
 * @param data 数据源数据
 * @returns 创建的数据源信息
 */
export const createDataSource = async (data: Omit<DataSource, 'id'>): Promise<DataSource> => {
  try {
    const { data: response } = await request.post<BaseResponse<DataSource>>('/api/datasources', data)
    ElMessage.success('创建数据源成功')
    return response.data
  } catch (error) {
    ElMessage.error('创建数据源失败')
    throw error
  }
}

/**
 * 更新数据源
 * @param data 数据源数据
 * @returns 更新后的数据源信息
 */
export const updateDataSource = async (data: DataSource): Promise<DataSource> => {
  try {
    const { data: response } = await request.put<BaseResponse<DataSource>>(`/api/datasources/${data.id}`, data)
    ElMessage.success('更新数据源成功')
    return response.data
  } catch (error) {
    ElMessage.error('更新数据源失败')
    throw error
  }
}

/**
 * 删除数据源
 * @param id 数据源ID
 */
export const deleteDataSource = async (id: number): Promise<void> => {
  try {
    await request.delete(`/api/datasources/${id}`)
    ElMessage.success('删除数据源成功')
  } catch (error) {
    ElMessage.error('删除数据源失败')
    throw error
  }
}

/**
 * 测试数据源连接
 * @param params 连接参数
 */
export const testConnection = async (params: TestConnectionParams): Promise<void> => {
  try {
    await request.post('/api/datasources/test-connection', params)
    ElMessage.success('连接测试成功')
  } catch (error) {
    ElMessage.error('连接测试失败')
    throw error
  }
}

// 缓存最近请求的数据源数据
const dataSourceCache = new Map<number, DataSource>()

/**
 * 获取数据源详情（带缓存）
 * @param id 数据源ID
 * @param forceRefresh 是否强制刷新缓存
 * @returns 数据源详情
 */
export const getDataSourceWithCache = async (id: number, forceRefresh = false): Promise<DataSource> => {
  if (!forceRefresh && dataSourceCache.has(id)) {
    return dataSourceCache.get(id)!
  }

  const dataSource = await getDataSource(id)
  dataSourceCache.set(id, dataSource)
  return dataSource
}
